<?php
include_once './fun.inc.php';
class Model{
    private static $db;
    private $table;
    public $error;
    public $errno;
    public $where;
    function __construct($table=null)
    {
       if($table){
           $this->table=$table;
       }

        if(!self::$db){
            try{
             self::$db=new PDO("mysql:host=".c('host_name').";dbname=".c('db_name').";charset=utf8",c('user'),c('pass'));

            }catch (PDOException $e){
                echo $e->getMessage();
            }
        }
    }

    public function add($date){

        $value=implode("','",$date);
        $keys=implode(',',array_keys($date));
        $sql="insert into ".$this->table."(".$keys." ) "."values ('".$value."')";
        $res= $this->exec($sql);
        $res=$res?$res:0;
        return "有受影响".$res.'条';
    }
    public  function  exec($sql){
        $res=self::$db->exec($sql);

        if(!$res){
            $this->error=self::$db->errorInfo()[2];
            $this->errno=self::$db->errorCode();
        }
        return $res;
    }

    public function find(){
        $sql="select * from ".$this->table.$this->where;
        var_dump($sql);
        return $this->query($sql);
    }
    public  function  where($where){
        $this->where=" where ".$where;
        return $this;
    }
    public function query($sql){
        $res=self::$db->query($sql);
        if(!$res){
            $this->error=self::$db->errorInfo()[2];
            $this->errno=self::$db->errorCode();
            return false;
        }
        return $res->fetchAll(PDO::FETCH_ASSOC);
    }
    public function getPri(){
        $sql="desc ".$this->table;
        $res=$this->query($sql);
        foreach($res as $v){
            if($v['Key']=='PRI'){
                return $v['Field'];
            }
        }
    }
    public function getError($no=null){
        if($no==1){
            return $this->errno;
        } elseif($no==2){
            return $this->error;
        }else{
            return $this->errno."和".$this->error;
        }
    }

    public function save($date){
        $str=" ";
        foreach($date as $k => $v){
            $str.=$k." =' ".$v."',";
        }
        $str=rtrim($str,',');
        $sql="update ".$this->table." set ".$str.$this->where;
        $res= $this->exec($sql);
        $res=$res?$res:0;
        return "有受影响".$res.'条';
    }

    public function delete($id=null){
        $key=$this->getPri();
        if($id){
            $sql="delete from ".$this->table." where ".$key." = ".$id;

        }else{
            $sql="delete from ".$this->table.$this->where;


        }
        $res=$this->exec($sql);
        $res=$res?$res:0;
        return "有受影响".$res.'条';
    }

}